package tables

import (
	"mini-admin/internal/open"
	v1 "mini-admin/internal/open/service/v1"

	// "github.com/Cluas/go-bytedance/bytedance"
	bytedance "gitee.com/quantum-force/bytedanceopen-api"
	"github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/modules/db"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
	"github.com/GoAdminGroup/go-admin/template/icon"
	"github.com/GoAdminGroup/go-admin/template/types/action"
	"github.com/GoAdminGroup/go-admin/template/types/form"
	"gorm.io/gorm"

	"mini-admin/internal/conf"
	"mini-admin/internal/database"
	"mini-admin/internal/model"
)

// GetBytedanceTemplate return the model of table system_templates.
func GetBytedanceTemplate(ctx *context.Context) (stTable table.Table) {

	stTable = table.NewDefaultTable(table.DefaultConfigWithDriver("postgresql"))

	info := stTable.GetInfo()
	info.AddField("ID", "id", db.Int).FieldSortable()
	info.AddField("模版ID", "template_id", db.Int)
	info.AddField("版本号", "user_version", db.Varchar)
	info.AddField("版本描述", "user_desc", db.Varchar)
	info.AddButton("同步字节跳动模版库", icon.Adjust, action.Ajax("sync_bytedance_template", func(ctx *context.Context) (success bool, msg string, data interface{}) {
		client := bytedance.NewClient()
		openClient := open.New(conf.Conf.OpenAddress)
		resp, err := openClient.ComponentAccessToken(ctx.Request.Context(), &v1.ComponentAccessTokenRequest{
			Platform: v1.Platform_PLATFORM_BYTEDANCE,
			AppId:    conf.Conf.BytedanceAppID,
		})
		if err != nil {
			return false, "", nil
		}
		templateList, _, err := client.ThirdParty.GetTemplates(ctx.Request.Context(), conf.Conf.BytedanceAppID, resp.ComponentAccessToken)
		if err != nil {
			return false, "", nil
		}
		conn := database.New(conf.Conf.ORM)
		var templates []*model.BytedanceTemplate
		conn.Model(&model.BytedanceTemplate{}).Find(&templates)
		ids := make(map[int]bool)
		idTemplateID := make(map[int64]int)
		for _, t := range templates {
			ids[t.TemplateID] = true
			idTemplateID[t.ID] = t.TemplateID
		}

		err = conn.Transaction(func(tx *gorm.DB) error {
			tIDs := make(map[int]bool)
			for _, t := range templateList.TemplateList {
				tIDs[t.TemplateID] = true
				if _, ok := ids[t.TemplateID]; !ok {
					newTemplate := model.BytedanceTemplate{
						TemplateID:  t.TemplateID,
						UserVersion: t.UserVersion,
						UserDesc:    t.UserDesc,
					}
					tx.Save(&newTemplate)
				}
			}
			var dIDs []int64
			for _, t := range templates {
				if _, ok := tIDs[t.TemplateID]; !ok {
					dIDs = append(dIDs, t.ID)
				}
			}
			tx.Delete(&model.BytedanceTemplate{}, dIDs)
			return nil
		})
		if err != nil {
			return false, "", nil
		}
		return true, "ok", nil

	}))
	info.SetTable("bytedance_template").SetTitle("字节跳动小程序模版").SetDescription("字节跳动小程序模版")

	formList := stTable.GetForm()
	formList.AddField("ID", "id", db.Int, form.Default).FieldDisplayButCanNotEditWhenUpdate().FieldDisableWhenCreate()
	formList.AddField("模版ID", "template_id", db.Int, form.Number)
	formList.AddField("版本号", "user_version", db.Varchar, form.Text)
	formList.AddField("版本描述", "user_desc", db.Varchar, form.Text)

	formList.SetTable("bytedance_template").SetTitle("字节跳动小程序模版").SetDescription("字节跳动小程序模版")

	return
}
